package com.hilaver.dzmis.web.listener;

import java.io.File;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.hilaver.dzmis.Constants;
import com.hilaver.dzmis.dao.HibernateSessionFactory;
import com.hilaver.dzmis.web.servlet.AbstractBaseServlet;

public class DZWebListener implements HttpSessionListener,
		ServletContextListener, ServletRequestListener {

	private static final String SERVLET_URI_FRAGMENT = "/servlet/";

	private long requestStartTime;
	private long requestEndTime;
	private String requestURI;

	@Override
	public void requestInitialized(ServletRequestEvent sre) {
		this.requestStartTime = System.currentTimeMillis();
		this.requestURI = ((HttpServletRequest) sre.getServletRequest())
				.getRequestURI();
		setLocale((HttpServletRequest) sre.getServletRequest());
		if (this.requestURI.indexOf(SERVLET_URI_FRAGMENT) != -1) {
			HibernateSessionFactory.getSession();
		}
	}

	@Override
	public void requestDestroyed(ServletRequestEvent sre) {
		HibernateSessionFactory.closeSession();
		this.requestEndTime = System.currentTimeMillis();
		 //System.err.println(this.requestURI + " takes " + (this.requestEndTime - this.requestStartTime) + " ms");
	}

	@Override
	public void sessionCreated(HttpSessionEvent se) {
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {

	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {

	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		if (AbstractBaseServlet.UPLOAD_TEMP_REAL_DIR == null) {
			AbstractBaseServlet.UPLOAD_TEMP_REAL_DIR = sce.getServletContext()
					.getRealPath(
							AbstractBaseServlet.UPLOAD_TEMP_DIR) + File.separator;
		}
		HibernateSessionFactory.getSession();
	}

	private static void setLocale(HttpServletRequest request) {
		if (request.getSession().getAttribute(Constants.SESSION_LOCALE) != null) {
			return;
		}
		request.getSession().setAttribute(Constants.SESSION_LOCALE,
				request.getLocale());
	}

}
